package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;


    @Override
    public R<LoginRespVo> login(LoginReqVo loginReqVo) {
        //1.判断用户名和密码是否存在
        if (loginReqVo == null
                || Strings.isNullOrEmpty(loginReqVo.getUsername())
                || Strings.isNullOrEmpty(loginReqVo.getPassword())
                || Strings.isNullOrEmpty(loginReqVo.getCode())
                || Strings.isNullOrEmpty(loginReqVo.getRkey())
        ) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //验证码校验
        //获取redis中rkey对应的code验证码
        String rCode = (String) redisTemplate.opsForValue().get(loginReqVo.getRkey());
        //校验
        if (rCode==null || !rCode.equals(loginReqVo.getCode())) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //redis清除key
//        redisTemplate.delete(loginReqVo.getRkey());
        //2.根据用户名查询用户信息，并判断用户是否存在
        SysUser user = sysUserMapper.findUserByUserName(loginReqVo.getUsername());
        if (user == null) {
            return R.error(ResponseCode.SYSTEM_USERNAME_NOT_EXISTS.getMessage());
        }
        //3.判断查询的db中的密码与前端传入的密码进行校验
        boolean flag = passwordEncoder.matches(loginReqVo.getPassword(), user.getPassword());
        if (!flag) {
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //成功，响应数据
        LoginRespVo respVo = new LoginRespVo();
        //属性值复制，前提：两个对象内的属性相同
        BeanUtils.copyProperties(user, respVo);
        return R.ok(respVo);
    }

    @Override
    public R<Map> generateCaptcha() {
        //1.生成4位数字验证码
        String checkCode = RandomStringUtils.randomNumeric(4);
        //2.获取全局唯一id
        String rkey = String.valueOf(idWorker.nextId());
        //验证码存入redis中，并设置有效期1分钟
        redisTemplate.opsForValue().set(rkey, checkCode, 60, TimeUnit.SECONDS);
        //3.组装数据
        Map<String, String> map = new HashMap<>();
        map.put("rkey", rkey);
        map.put("code", checkCode);
        return R.ok(map);
    }
}
